<script lang="ts" name="syscustomer" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { formatDate } from '/@/utils/formatTime';
import { generateCustomerCode } from '/@/utils/generateCode';
import { useSyscustomerApi } from '/@/api/interacting/syscustomer';
import { useSysOrgApi } from '/@/api/system/sysOrg';
import { useSysUserApi } from '/@/api/system/sysUser';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const syscustomerApi = useSyscustomerApi();
const sysOrgApi = useSysOrgApi();
const sysUserApi = useSysUserApi();
const ruleFormRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	// 下拉框数据
	orgList: [] as any[],
	userList: [] as any[],
	filteredUserList: [] as any[], // 根据部门筛选后的用户列表
	// 所属行业选项
	industryOptions: [
		'旅游服务',
		'国际贸易',
		'新能源',
		'花卉种植',
		'农业',
		'汽车配件',
		'化工',
		'文化传媒',
		'港口物流',
		'食品加工',
		'建筑工程',
		'医疗器械',
		'物流运输',
		'电子商务',
		'教育',
		'服务业',
		'制造业',
		'贸易',
		'信息技术'
	],
	// 客户来源选项
	customerSourceOptions: [
		'政府合作',
		'边境贸易',
		'技术合作',
		'电商平台',
		'政府扶持',
		'OEM合作',
		'行业交流',
		'创意合作',
		'网络营销',
		'战略合作',
		'供应商推荐',
		'政府招标',
		'行业展会',
		'合作伙伴介绍',
		'广告投放',
		'网络搜索',
		'电话营销',
		'展会',
		'客户推荐',
		'网络推广'
	]
});

// 自行添加其他规则
const rules = ref<FormRules>({
	code: [{ required: true, message: '请选择客户编码！', trigger: 'blur', },],
	customerName: [{ required: true, message: '请选择客户名称！', trigger: 'blur', },],
	status: [{ required: true, message: '请选择状态！', trigger: 'blur', },],
	orderNo: [{ required: true, message: '请选择排序！', trigger: 'blur', },],
});

// 部门变化时筛选用户
const onDeptChange = (deptId: number) => {
	if (deptId) {
		// 根据部门ID筛选用户
		state.filteredUserList = state.userList.filter(user => user.orgId === deptId);
	} else {
		// 如果没有选择部门，显示所有用户
		state.filteredUserList = state.userList;
	}
	// 清空已选择的负责人
	state.ruleForm.salesManagerId = null;
};

// 页面加载时
onMounted(async () => {
	// 加载机构列表
	try {
		const orgRes = await sysOrgApi.getList();
		state.orgList = orgRes.data.result || [];
	} catch (error) {
		console.error('加载机构列表失败:', error);
	}

	// 加载用户列表
	try {
		const userRes = await sysUserApi.getList();
		state.userList = userRes.data.result || [];
		state.filteredUserList = userRes.data.result || []; // 初始显示所有用户
	} catch (error) {
		console.error('加载用户列表失败:', error);
	}
});

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? { orderNo: 100, };
	
	if (row.id) {
		// 编辑模式：获取完整数据
		state.ruleForm = await syscustomerApi.detail(row.id).then(res => res.data.result);
	} else {
		// 新增模式：初始化表单数据，自动生成客户编码
		state.ruleForm = {
			...JSON.parse(JSON.stringify(row)),
			code: generateCustomerCode(), // 客户编码 - 自动生成
		};
	}
	
	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = state.ruleForm;
			await syscustomerApi[state.ruleForm.id ? 'update' : 'add'](values);
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>

	

	<div class="syscustomer-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="客户编码" prop="code">
							<el-input 
								v-model="state.ruleForm.code" 
								placeholder="客户编码" 
								maxlength="64" 
								show-word-limit
								:readonly="true"
								style="background-color: #f5f7fa;"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="客户名称" prop="customerName">
							<el-input v-model="state.ruleForm.customerName" placeholder="请输入客户名称" maxlength="128"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="所属行业" prop="industry">
							<el-select v-model="state.ruleForm.industry" placeholder="请选择所属行业" clearable filterable>
								<el-option v-for="industry in state.industryOptions" :key="industry" :label="industry"
									:value="industry" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="客户来源" prop="customerSource">
							<el-select v-model="state.ruleForm.customerSource" placeholder="请选择客户来源" clearable
								filterable>
								<el-option v-for="source in state.customerSourceOptions" :key="source" :label="source"
									:value="source" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="联系人" prop="contactPerson">
							<el-input v-model="state.ruleForm.contactPerson" placeholder="请输入联系人" maxlength="64"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="联系电话" prop="contactPhone">
							<el-input v-model="state.ruleForm.contactPhone" placeholder="请输入联系电话" maxlength="32"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="电子邮箱" prop="email">
							<el-input v-model="state.ruleForm.email" placeholder="请输入电子邮箱" maxlength="128"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="销售部门" prop="salesDeptId">
							<el-select v-model="state.ruleForm.salesDeptId" placeholder="请选择销售部门" clearable filterable
								@change="onDeptChange">
								<el-option v-for="org in state.orgList" :key="org.id" :label="org.name"
									:value="org.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="销售负责人" prop="salesManagerId">
							<el-select v-model="state.ruleForm.salesManagerId" placeholder="请选择销售负责人" clearable
								filterable>
								<el-option v-for="user in state.filteredUserList" :key="user.id" :label="user.realName"
									:value="user.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状态" prop="status">
							<el-switch 
								v-model="state.ruleForm.status" 
								:active-value="1" 
								:inactive-value="0"
								active-text="启用" 
								inactive-text="禁用"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="客户地址" prop="customerAddress">
							<el-input v-model="state.ruleForm.customerAddress" placeholder="请输入客户地址" maxlength="256"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" maxlength="512"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="账户名称" prop="accountName">
							<el-input v-model="state.ruleForm.accountName" placeholder="请输入账户名称" maxlength="128"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="纳税人识别号" prop="taxpayerId">
							<el-input v-model="state.ruleForm.taxpayerId" placeholder="请输入纳税人识别号" maxlength="32"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="银行账户" prop="bankAccount">
							<el-input v-model="state.ruleForm.bankAccount" placeholder="请输入银行账户" maxlength="32"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="开户银行" prop="openingBank">
							<el-input v-model="state.ruleForm.openingBank" placeholder="请输入开户银行" maxlength="128"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="开户行地址" prop="openingBankAddress">
							<el-input v-model="state.ruleForm.openingBankAddress" placeholder="请输入开户行地址" maxlength="256"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序" prop="orderNo">
							<el-input-number v-model="state.ruleForm.orderNo" placeholder="请输入排序" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="软删除时间" prop="deleteTime">
							<el-date-picker v-model="state.ruleForm.deleteTime" type="date" placeholder="软删除时间" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false">取 消</el-button>
					<el-button @click="submit" type="primary" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
